package com.gis.controller;

import com.gis.utils.CommonUtil;
import com.gis.utils.GeoserverUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@RestController
@RequiredArgsConstructor
@RequestMapping("/geoserver")
public class GeoserverController {
    //构造器注入要声明为final
    private final GeoserverUtil geoserverUtil;
    private final CommonUtil commonUtil;
    @PostMapping("/uploadshp")
    public ResponseEntity<String> uploadShapefile(@RequestParam("file") MultipartFile file,
                                                  @RequestParam("workspace") String workspace,
                                                  @RequestParam("storeName") String storeName) {
        try {
            // 将MultipartFile转换为File对象
            File convertedFile = commonUtil.convertMultipartFileToFile(file);

            // 上传 Shapefile 并发布
            String geoPath="/data/geoserver/shapefiles/";
            String shpName="shp";
            String styleName="point";
            String url= geoserverUtil.uploadShp2GeoServer(convertedFile, workspace, storeName,geoPath,shpName,styleName);

            // 删除临时文件
            convertedFile.delete();

            return ResponseEntity.ok("Shapefile uploaded and published successfully: "+url);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("Failed to upload Shapefile: " + e.getMessage());
        }
    }
    @PostMapping("/uploadtif")
    public ResponseEntity<String> uploadTifFile(@RequestParam("file") MultipartFile file,
                                                  @RequestParam("workspace") String workspace,
                                                  @RequestParam("storeName") String storeName) {
        try {
            // 将MultipartFile转换为File对象
            File convertedFile = commonUtil.convertMultipartFileToFile(file);

            // 上传 Shapefile 并发布
            String geoPath="/data/geoserver/tiffiles/";
            String tifName="tif";
            String styleName="point";
            String url= geoserverUtil.uploadTif2GeoServer(convertedFile, workspace, storeName,geoPath,tifName,styleName);

            // 删除临时文件
            convertedFile.delete();

            return ResponseEntity.ok("栅格上传成功: "+url);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("栅格上传失败: " + e.getMessage());
        }
    }





}
